import VideoAbstract from './VideoAbstract';
import type { PropsType } from './CommonVideoPlayer';

export default class DhFlvVideo extends VideoAbstract {
	private static instance: DhFlvVideo | null;
	private flvPlayer: Window['dhflvjs'] | null;
	private videoElement: HTMLVideoElement | undefined;

	private constructor(props: PropsType['dhflv']) {
		super();
		this.flvPlayer = window.dhflvjs.createPlayer({
			type: props.type || 'flv',
			url: props.url,
			isLive: props.isLive || false,
			hasAudio: props.hasAudio || false,
		});

		this.bindVideo(props.el);

		console.log('dhflv实例化成功');
	}

	static getInstance(props: PropsType['dhflv']): DhFlvVideo {
		return DhFlvVideo.instance || (DhFlvVideo.instance = new DhFlvVideo(props));
	}

	bindVideo(video: HTMLVideoElement): void {
		this.videoElement = video;
		this.flvPlayer?.attachMediaElement(video);
		this.flvPlayer?.load();
	}
	unbindVideo(): void {
		this.flvPlayer?.detachMediaElement();
	}
	setCurrentTime(time: number): void {
		if (this.flvPlayer) this.flvPlayer.currentTime = time;
	}
	play(): void {
		this.flvPlayer?.play();
	}
	pause(): void {
		this.flvPlayer?.pause();
	}

	destroy() {
		try {
			if (this.flvPlayer !== null) {
				// this.flvPlayer?.off(window.dhflvjs.Events.ERROR, () => {
				// 	console.log('flv错误监听卸载');
				// });

				this.flvPlayer?.destroy();
				this.flvPlayer = null;
				this.unbindVideo();
			}
			this.videoElement?.removeEventListener('loadeddata', () => {
				console.log('loadeddata卸载');
			});
			DhFlvVideo.instance = null;
		} catch (err) {
			console.error(err);
		}
	}

	// 加载完成
	onLoaded(callback: (data: any) => void): void {
		this.videoElement?.addEventListener('loadeddata', (e) => {
			callback(e);
		});
	}

	// 播放中
	onPlaying(callback: (data: any) => void): void {
		this.videoElement?.addEventListener('timeupdate', (e) => {
			callback(e);
		});
	}

	// 播放完成
	onPlayEnd(callback: (data: any) => void): void {
		this.videoElement?.addEventListener('ended', (e) => {
			callback(e);
		});
	}

	onError(callback?: (error: any) => void): void {
		this.flvPlayer?.on(window.dhflvjs.Events.ERROR, (e: any) => {
			console.error('flv-error', e);
			if (typeof callback === 'function') callback(e);
		});
	}
}
